<template>
  <div class="qrcode-attendance">
    <el-card class="form-card">
      <div slot="header">
        <span>创建二维码签到</span>
      </div>
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="签到标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入签到标题"></el-input>
        </el-form-item>
        <el-form-item label="选择班级" prop="classroomId">
          <el-select v-model="form.classroomId" placeholder="请选择班级" style="width: 100%">
            <el-option
              v-for="item in classrooms"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.code }} ({{ item.studentCount }}人)
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">生成二维码</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 二维码显示区域 -->
    <el-card class="qrcode-card" v-if="qrCodeData">
      <div slot="header">
        <span>签到二维码</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="downloadQRCode">下载二维码</el-button>
      </div>
      <div class="qrcode-container">
        <div id="qrcode" ref="qrcode"></div>
        <div class="qrcode-info">
          <p>签到标题：{{ form.title }}</p>
          <p>班级：{{ selectedClassroomName }}</p>
          <p>开始时间：{{ form.startTime }}</p>
          <p>结束时间：{{ form.endTime }}</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'

export default {
  name: 'QRCodeAttendance',
  data() {
    return {
      form: {
        title: '',
        classroomId: '',
        startTime: '',
        endTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入签到标题', trigger: 'blur' }
        ],
        classroomId: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },
      classrooms: [],
      loading: false,
      qrCodeData: null
    }
  },
  computed: {
    selectedClassroomName() {
      const classroom = this.classrooms.find(item => item.id === this.form.classroomId)
      return classroom ? classroom.name : ''
    }
  },
  created() {
    this.getClassrooms()
  },
  methods: {
    // 获取班级列表
    async getClassrooms() {
      try {
        const res = await this.$http.get('/api/teacher/classroom/list')
        this.classrooms = res.data.records
      } catch (error) {
        this.$message.error('获取班级列表失败')
      }
    },
    // 生成二维码
    generateQRCode() {
      // 清除旧的二维码
      this.$refs.qrcode.innerHTML = ''

      // 生成新的二维码
      new QRCode(this.$refs.qrcode, {
        text: this.qrCodeData.qrCodeUrl,
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    // 提交表单
    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true
          let res
          try {
            res = await this.$http.post('/api/teacher/attendance/qrcode', this.form)
            if (res.code === 1) {
              this.qrCodeData = res.data
              this.$nextTick(() => {
                this.generateQRCode()
              })
              this.$message.success('二维码生成成功')
            } else {
              this.$message.error(res.msg)
            }
          } catch (error) {
            if (error.response && error.response.data) {
              this.$message.error(error.response.data.msg)
            } else {
              this.$message.error('生成二维码失败')
            }
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 下载二维码
    downloadQRCode() {
      const canvas = this.$refs.qrcode.querySelector('canvas')
      const link = document.createElement('a')
      link.download = `${this.form.title}.png`
      link.href = canvas.toDataURL()
      link.click()
    }
  }
}
</script>

<style scoped>
.qrcode-attendance {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.qrcode-card {
  margin-bottom: 20px;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 20px;
}

.qrcode-info {
  margin-top: 20px;
  text-align: center;
}

.qrcode-info p {
  margin: 5px 0;
  color: #606266;
}

#qrcode {
  margin: 20px;
}
</style>
